<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>类别点击量分析 - 纵横小说推荐榜数据可视化平台</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
    <link rel="stylesheet" href="{{ url_for('static', filename='css/chart-styles.css') }}">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.2/dist/echarts.min.js"></script>
</head>
<body>
    <!-- 顶部区域 -->
    <header class="header">
        <img src="{{ url_for('static', filename='images/logo.png') }}" alt="Logo" class="logo">
        <h1 class="system-title">纵横小说推荐榜数据可视化平台</h1>
    </header>

    <!-- 左侧导航栏 -->
    <nav class="sidebar">
        <a href="/" class="nav-item">
            <i class="fas fa-book-open fa-fw"></i>
            <span>图书列表</span>
        </a>
        <a href="/charts" class="nav-item">
            <i class="fas fa-chart-pie fa-fw"></i>
            <span>书籍类别分布</span>
        </a>
        <a href="/bar-chart" class="nav-item active">
            <i class="fas fa-chart-bar fa-fw"></i>
            <span>类别点击量分析</span>
        </a>
        <a href="/line-chart" class="nav-item">
            <i class="fas fa-chart-line fa-fw"></i>
            <span>字数与推荐数关系</span>
        </a>
        <a href="/boxplot" class="nav-item">
            <i class="fas fa-chart-simple fa-fw"></i>
            <span>状态与周推荐数</span>
        </a>
        <a href="/ranking-chart" class="nav-item">
            <i class="fas fa-trophy fa-fw"></i>
            <span>书籍点击量排名</span>
        </a>
    </nav>

    <!-- 主内容区 -->
    <main class="main-content">
        <h2 class="page-title">类别点击量分析</h2>

        <div class="chart-container">
            <div class="chart-header">
                <h3 class="chart-title">
                    <i class="fas fa-chart-bar"></i>
                    各类别平均点击量
                </h3>
                <div class="chart-actions">
                    <div class="chart-filter">
                        <label for="sortSelect">排序方式：</label>
                        <select id="sortSelect" class="filter-select">
                            <option value="value-desc">点击量降序</option>
                            <option value="value-asc">点击量升序</option>
                            <option value="name-asc">类别名称升序</option>
                            <option value="name-desc">类别名称降序</option>
                        </select>
                    </div>
                    <button id="downloadBtn" class="action-button">
                        <i class="fas fa-download"></i>
                        <span>下载图表</span>
                    </button>
                    <button id="refreshBtn" class="action-button">
                        <i class="fas fa-sync-alt"></i>
                        <span>刷新数据</span>
                    </button>
                </div>
            </div>

            <div class="chart-description">
                <i class="fas fa-info-circle"></i>
                <p>此图表展示了纵横小说推荐榜中各类别书籍的平均点击量，反映了不同类型小说的受欢迎程度。</p>
            </div>

            <div id="loadingIndicator" class="loading">
                <div class="loading-spinner"></div>
            </div>

            <div id="chart" class="chart"></div>
        </div>

        <div class="chart-container">
            <div class="chart-header">
                <h3 class="chart-title">
                    <i class="fas fa-chart-bar"></i>
                    点击量与推荐数对比
                </h3>
            </div>

            <div class="chart-description">
                <i class="fas fa-info-circle"></i>
                <p>此图表对比展示了各类别书籍的平均点击量和平均推荐数，帮助分析点击量与推荐数之间的关系。</p>
            </div>

            <div id="loadingIndicator2" class="loading">
                <div class="loading-spinner"></div>
            </div>

            <div id="comparisonChart" class="chart"></div>
        </div>
    </main>

    <script>
        // 初始化ECharts实例
        var chartDom = document.getElementById('chart');
        var myChart = echarts.init(chartDom);

        var comparisonChartDom = document.getElementById('comparisonChart');
        var comparisonChart = echarts.init(comparisonChartDom);

        var chartData = [];

        // 显示加载状态
        function showLoading(id = 'loadingIndicator') {
            document.getElementById(id).style.display = 'flex';
        }

        // 隐藏加载状态
        function hideLoading(id = 'loadingIndicator') {
            document.getElementById(id).style.display = 'none';
        }

        // 获取图表数据
        async function fetchChartData() {
            showLoading();
            showLoading('loadingIndicator2');

            try {
                const response = await fetch('/api/category-clicks');
                if (!response.ok) {
                    throw new Error('网络请求失败');
                }

                chartData = await response.json();
                renderBarChart();
                renderComparisonChart();
            } catch (error) {
                console.error('获取数据失败:', error);
                myChart.showLoading({
                    text: '数据加载失败，请刷新重试',
                    maskColor: 'rgba(255, 255, 255, 0.8)',
                    textColor: '#ff4d4f'
                });
                comparisonChart.showLoading({
                    text: '数据加载失败，请刷新重试',
                    maskColor: 'rgba(255, 255, 255, 0.8)',
                    textColor: '#ff4d4f'
                });
            } finally {
                hideLoading();
                hideLoading('loadingIndicator2');
            }
        }

        // 排序数据
        function sortData(data, sortType) {
            const sortedData = [...data];

            switch (sortType) {
                case 'value-desc':
                    sortedData.sort((a, b) => b.value - a.value);
                    break;
                case 'value-asc':
                    sortedData.sort((a, b) => a.value - b.value);
                    break;
                case 'name-asc':
                    sortedData.sort((a, b) => a.name.localeCompare(b.name));
                    break;
                case 'name-desc':
                    sortedData.sort((a, b) => b.name.localeCompare(a.name));
                    break;
                default:
                    sortedData.sort((a, b) => b.value - a.value);
            }

            return sortedData;
        }

        // 渲染柱状图
        function renderBarChart() {
            const sortType = document.getElementById('sortSelect').value;
            const sortedData = sortData(chartData, sortType);

            const option = {
                title: {
                    text: '各类别平均点击量(万)',
                    left: 'center'
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    },
                    formatter: '{b}: {c} 万'
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '15%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    data: sortedData.map(item => item.name),
                    axisLabel: {
                        interval: 0,
                        rotate: 45,
                        textStyle: {
                            fontSize: 12
                        }
                    }
                },
                yAxis: {
                    type: 'value',
                    name: '平均点击量(万)'
                },
                series: [
                    {
                        name: '平均点击量',
                        type: 'bar',
                        data: sortedData.map(item => item.value),
                        itemStyle: {
                            color: function(params) {
                                // 生成渐变色
                                const colorList = [
                                    '#1890ff', '#13c2c2', '#52c41a', '#faad14', '#f5222d',
                                    '#722ed1', '#eb2f96', '#fa8c16', '#a0d911', '#fadb14',
                                    '#2f54eb', '#fa541c', '#391085', '#9254de', '#36cfc9'
                                ];
                                return colorList[params.dataIndex % colorList.length];
                            },
                            borderRadius: [5, 5, 0, 0]
                        },
                        emphasis: {
                            itemStyle: {
                                shadowBlur: 10,
                                shadowOffsetX: 0,
                                shadowColor: 'rgba(0, 0, 0, 0.5)'
                            }
                        },
                        animationDelay: function (idx) {
                            return idx * 50;
                        }
                    }
                ],
                animationEasing: 'elasticOut',
                animationDelayUpdate: function (idx) {
                    return idx * 5;
                }
            };

            myChart.setOption(option);
        }

        // 渲染对比图表
        function renderComparisonChart() {
            // 假设我们有点击量和推荐数的数据
            // 实际应用中，这些数据应该从API获取
            const clicksData = chartData.map(item => ({
                name: item.name,
                value: item.value
            }));

            // 模拟推荐数据（实际应用中应从API获取）
            const recommendationsData = chartData.map(item => ({
                name: item.name,
                value: (item.value * 0.3 + Math.random() * 10).toFixed(2)
            }));

            const sortType = document.getElementById('sortSelect').value;
            const sortedClicks = sortData(clicksData, sortType);

            // 确保推荐数据与点击量数据顺序一致
            const categories = sortedClicks.map(item => item.name);
            const sortedRecommendations = categories.map(category => {
                return recommendationsData.find(item => item.name === category);
            });

            const option = {
                title: {
                    text: '点击量与推荐数对比(万)',
                    left: 'center'
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    }
                },
                legend: {
                    data: ['平均点击量', '平均推荐数'],
                    top: 30
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '15%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    data: categories,
                    axisLabel: {
                        interval: 0,
                        rotate: 45,
                        textStyle: {
                            fontSize: 12
                        }
                    }
                },
                yAxis: {
                    type: 'value',
                    name: '数量(万)'
                },
                series: [
                    {
                        name: '平均点击量',
                        type: 'bar',
                        data: sortedClicks.map(item => item.value),
                        itemStyle: {
                            color: '#1890ff',
                            borderRadius: [5, 5, 0, 0]
                        }
                    },
                    {
                        name: '平均推荐数',
                        type: 'bar',
                        data: sortedRecommendations.map(item => item.value),
                        itemStyle: {
                            color: '#52c41a',
                            borderRadius: [5, 5, 0, 0]
                        }
                    }
                ]
            };

            comparisonChart.setOption(option);
        }

        // 下载图表
        document.getElementById('downloadBtn').addEventListener('click', function() {
            const link = document.createElement('a');
            link.download = '类别点击量分析.png';
            link.href = myChart.getDataURL({
                type: 'png',
                pixelRatio: 2,
                backgroundColor: '#fff'
            });
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        });

        // 排序变化时重新渲染图表
        document.getElementById('sortSelect').addEventListener('change', function() {
            renderBarChart();
            renderComparisonChart();
        });

        // 刷新数据
        document.getElementById('refreshBtn').addEventListener('click', fetchChartData);

        // 响应窗口大小变化
        window.addEventListener('resize', function() {
            myChart.resize();
            comparisonChart.resize();
        });

        // 页面加载完成后获取数据
        document.addEventListener('DOMContentLoaded', fetchChartData);
    </script>
</body>
</html>
